package com.anzia.study_11.slice;

import com.anzia.study_11.ResourceTable;
import com.anzia.study_11.utils.UIUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.render.opengl.Utils;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;

import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {

	private Button btn1, btn2, btn3, btn4, btn5, btn6;
	private KvManagerConfig kvManagerConfig;
	private KvManager kvManager;
	private String storeId = "kvStoreDemo";
	private SingleKvStore singleKvStore;

	private class KvStoreObserverClient implements KvStoreObserver {
		@Override
		public void onChange(ChangeNotification changeNotification) {
			// onChange，分布式数据库里的数据发生编号，就会回调这个方法
			// List<Entry> insertEntries = changeNotification.getInsertEntries();
			System.out.println("========onChange");
		}
	}

	@Override
	public void onStart(Intent intent) {
		super.onStart(intent);
		super.setUIContent(ResourceTable.Layout_ability_main);

		btn1 = (Button) findComponentById(ResourceTable.Id_btn_1);
		btn1.setClickedListener(mClickedListener);
		btn2 = (Button) findComponentById(ResourceTable.Id_btn_2);
		btn2.setClickedListener(mClickedListener);
		btn3 = (Button) findComponentById(ResourceTable.Id_btn_3);
		btn3.setClickedListener(mClickedListener);
		btn4 = (Button) findComponentById(ResourceTable.Id_btn_4);
		btn4.setClickedListener(mClickedListener);
		btn5 = (Button) findComponentById(ResourceTable.Id_btn_5);
		btn5.setClickedListener(mClickedListener);
		btn6 = (Button) findComponentById(ResourceTable.Id_btn_6);
		btn6.setClickedListener(mClickedListener);

		// 不使用谓词查询就是三大步，如果要使用谓词查询，不只是三步
		// 构造谓词查询中使用的字段
		FieldNode fdid = new FieldNode("id");
		fdid.setNullable(false);

		FieldNode fdname = new FieldNode("name");
		fdname.setType(FieldValueType.STRING);

		FieldNode fdage = new FieldNode("age");
		fdage.setType(FieldValueType.INTEGER);

		Schema schema = new Schema();
		ArrayList<String> indexsList = new ArrayList<>();
		indexsList.add("$.id"); // 写法很重要，规定
		schema.setIndexes(indexsList);
		// 所有的字段喝schema对象关联，绑定起来
		schema.getRootFieldNode().appendChild(fdid);
		schema.getRootFieldNode().appendChild(fdname);
		schema.getRootFieldNode().appendChild(fdage);
		// 兼容模式
		schema.setSchemaMode(SchemaMode.COMPATIBLE);



		kvManagerConfig = new KvManagerConfig(this);
		kvManager = KvManagerFactory.getInstance().createKvManager(kvManagerConfig);
		Options options = new Options();
		options.setCreateIfMissing(true).setAutoSync(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
		// 谓词查询所用的
		options.setSchema(schema);
		// options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);

		System.out.println(options.getKvStoreType());
		System.out.println(options.isAutoSync());
		System.out.println(options.isBackup());
		System.out.println(options.isCreateIfMissing());
		System.out.println(options.isEncrypt());

		singleKvStore = kvManager.getKvStore(options, storeId); // 拿到数据库

		// 把观察者喝数据库绑定
		KvStoreObserverClient kvStoreObserverClient = new KvStoreObserverClient();
		singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient);

	}

	private Component.ClickedListener mClickedListener = new Component.ClickedListener() {
		@Override
		public void onClick(Component component) {
			int componentId = component.getId();
			switch (componentId) {
				case ResourceTable.Id_btn_1: {
					// 写入数据
					try {
						// singleKvStore.putString("test", "HarmonyOS NO.1");
						singleKvStore.putString("key_1", "{\"id\":1,\"name\":\"Anzia\",\"age\":18}");
						singleKvStore.putString("key_2", "{\"id\":2,\"name\":\"Abc\",\"age\":28}");
						singleKvStore.putString("key_3", "{\"id\":3,\"name\":\"Apple\",\"age\":38}");
						System.out.println("=======写入数据成功");
						UIUtils.showTip(MainAbilitySlice.this, "写入数据成功");
					} catch (KvStoreException e) {
						e.printStackTrace();
					}
				} break;
				case ResourceTable.Id_btn_2: {
					// 删除数据
					try {
						singleKvStore.delete("key_1");
						System.out.println("=======删除数据成功");
						UIUtils.showTip(MainAbilitySlice.this, "删除数据成功");
					} catch (KvStoreException e) {
						e.printStackTrace();
					}
				} break;
				case ResourceTable.Id_btn_3: {
					// 读数据
					try {
						// singleKvStore.getString("test");
						// System.out.println("=======读取数据成功");
						// UIUtils.showTip(MainAbilitySlice.this, "读取数据成功");
						Query query = Query.select(); // Query查询的算子，查询的条件
						query.equalTo("$.id", 2);
						List<Entry> entries = singleKvStore.getEntries(query);
						// KvStoreResultSet resultSet = singleKvStore.getResultSet(query);
						if (entries.size() > 0) {
							System.out.println("======: " + entries.get(0).getValue().getString());
							UIUtils.showTip(MainAbilitySlice.this, entries.get(0).getValue().getString());
						}
					} catch (KvStoreException e) {
						e.printStackTrace();
					}
				} break;
				case ResourceTable.Id_btn_4: {
					// 关闭数据库
					try {
						kvManager.closeKvStore(singleKvStore);
						System.out.println("=======关闭数据库成功");
						UIUtils.showTip(MainAbilitySlice.this, "关闭数据库成功");
					} catch (KvStoreException e) {
						e.printStackTrace();
					}
				} break;
				case ResourceTable.Id_btn_5: {
					// 删除数据库
					try {
						kvManager.deleteKvStore(storeId);
						System.out.println("=======删除数据库成功");
						UIUtils.showTip(MainAbilitySlice.this, "删除数据库成功");
					} catch (KvStoreException e) {
						e.printStackTrace();
					}
				}; break;
				case ResourceTable.Id_btn_6: {
					// 数据同步
					try {
						List<DeviceInfo> deviceList = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
						ArrayList<String> deviceIds = new ArrayList<>();
						for (DeviceInfo deviceInfo : deviceList) {
							deviceIds.add(deviceInfo.getDeviceId());
						}
						singleKvStore.sync(deviceIds, SyncMode.PUSH_PULL);
						System.out.println("=======同步数据库成功");
						UIUtils.showTip(MainAbilitySlice.this, "同步数据库成功");
					} catch (KvStoreException e) {
						e.printStackTrace();
					}
				};
			}
		}
	};


	@Override
	public void onActive() {
		super.onActive();
	}

	@Override
	public void onForeground(Intent intent) {
		super.onForeground(intent);
	}
}
